
package PurlExt::creature;
use strict;

sub import {
    Purl::Commands::register(
        name   => '@creature',
        subRef => \&PurlExt::creature::creature,
    );
    Purl::Commands::register(
        name                  => 'forceCreature',
        subRef                => \&PurlExt::creature::force_creature,
        aliases               => "%",
        shortCommandException => 1
    );
}

sub creature {
    my %args = @_;
    Purl::comm::sendTextToPlayer(
        target => $args{actor},
        text   => "Syntax: \@creature object"
        )
        if ( $args{text} eq "" );
    ( $args{target}, $args{text} ) = split( " ", $args{text}, 2 );
    my $id;    
    if ( substr( $args{target}, 0, 1 ) eq "#" ) {

        $id = substr( $args{target}, 1 );
        $id = &main::idBounds($id);
    }
    else {
        $id = &findContents( $main::objects[ $args{actor} ]{"location"},
            $args{target} );
        $id = &findContents( $args{actor}, $args{target} )
            if ( $id == $main::none );
    }
    if ( $id == $main::none ) {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "I don't see that object here."
        );
        return;
    }
    if (   ( !&Purl::tests::isWizard( $args{actor} ) )
        && ( $main::objects[$id]{"owner"} != $args{actor} ) )
    {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "You don't own that."
        );
        return;
    }
    my $name = $main::objects[$id]{"name"};
    $name =~ tr/A-Z/a-z/;
    if ( exists( $main::playerIds{$name} ) ) {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "That is not a good name for your creature."
        );
        return;
    }
    $main::playerIds{$name} = $id;
    $main::objects[$id]{"flags"} &= $main::flags{"creature"}{"value"};
    Purl::comm::sendTextToPlayer(
        target => $args{actor},
        text   => "Your creature is activated."
    );
    Purl::comm::sendTextToPlayer(
        target => $id,
        text   => "Testing your creature."
    );
}

sub force_creature {
    my %args = @_;
    if ( $args{text} !~ /\s+/ ) {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "Usage: %<name> <command>"
        );
        return;
    }
    my ( $creature, $command ) = split( " ", $args{text}, 2 );
    $creature =~ tr/A-Z/a-z/;
    if ( !exists( $main::playerIds{$creature} ) ) {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "Sorry, that is not a valid creature."
        );
        return;
    }
    elsif ( $main::objects[ $main::playerIds{$creature} ]{"owner"}
        != $args{actor} )
    {
        Purl::comm::sendTextToPlayer(
            target => $args{actor},
            text   => "Permission denied."
        );
        return;
    }
    &command( $main::playerIds{$creature}, $command );
}

1;

